from django.shortcuts import render
from django.views import View
from headlines.serializers import *
from rest_framework.generics import ListAPIView, RetrieveAPIView, CreateAPIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Q
from tenthpower.utils.paginator import Pagination


# 还需导入分页器

# Create your views here.

# 1.频道列表
class ChannelView(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = ChannelModelSerializer
    pagination_class = Pagination


# 2.文章列表
class ArticleView(ListAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleModelSerializer

    pagination_class = Pagination

    def get_queryset(self):
        channel_id = self.kwargs.get('id')

        if channel_id == -1:
            return self.queryset.all()
        else:
            return self.queryset.filter(channel_id=channel_id)


# 3.收藏或取消收藏
class StarOrNotArticleView(APIView):
    def put(self, request, id):
        cur_article = Article.objects.get(id=id)

        # 取消收藏
        if cur_article.collected:
            cur_article.collected = False
            return Response({
                'message': '取消收藏成功',
                'success': True
            })

        # 收藏
        if not cur_article.collected:
            cur_article.collected = True
            return Response(data={
                'message': '收藏成功',
                'success': True
            })


# 4.文章详情
class DetailOfArticleView(RetrieveAPIView):
    queryset = Article.objects.all()
    serializer_class = DetailOfArticleModelSerializer


# 5.发布文章
class ReleaseArticleView(APIView):
    def post(self, request, *args, **kwargs):
        ret = ReleaseArticleModelSerializer(data=request.data)

        ret.is_valid(raise_exception=True)

        article = ret.save()

        return Response(data={
            'articleid': article.id,
            'message': "ok",
            'success': True
        })


# 6.评论文章
class CommentArticleView(APIView):
    def post(self, request, pk):
        cur_comment = Comment.objects.get(article__id=pk)

        cur_comment.content = request.data.get('content')
        cur_comment.parent = request.data.get('parent')

        return Response(data={
            'message': "ok",
            "success": True
        })


# 7.搜素文章
class SearchArticleView(ListAPIView):
    queryset = Article.objects.all()
    serializers = SearchArticleModelSerializer
    pagination_class = Pagination

    def get_queryset(self):
        search_kw = self.request.query_params.get('text')
        if search_kw:
            return self.queryset.filter(Q(title__contains=search_kw) | Q(content__contains=search_kw))

        return self.queryset.all()
